import React, { useState, useEffect } from 'react';
import SelfHead from 'components/common/selfHead';
import Cascade from 'components/common/cascade';
import { List, Toast, InputItem } from 'antd-mobile';
import { createForm } from 'rc-form';
import Star from 'components/common/star';
import SelfRadio from 'components/common/selfRadio';
import SelfInput from 'components/common/selfInput';
import TimePicker from 'components/common/timePicker';
import { getSite, getDicType, addSupply } from 'ser/actions';
import { transTime } from 'utils/time';
import { history } from 'umi';
import './index.less';
let oneYear = 365 * 24 * 60 * 60 * 1000;
let current = new Date().getTime();
function Add(props) {
  const user = JSON.parse(sessionStorage.getItem('user'));
  // 一级省份数据
  const [province, setProvince] = useState([]);
  // 所有地点数据
  const [site, setSite] = useState([]);
  const [type, setType] = useState([]);
  const [natWay, setNatWay] = useState([]);
  const [coldWay, setColdWay] = useState([]);
  const [way, setWay] = useState([]);
  const [unit, setUnit] = useState('吨');
  const [validityType, setValidityType] = useState('');
  const [showValidity, setShowValidity] = useState(false);
  const [flag, setFlag] = useState(false);
  const [obj, setObj] = useState({
    deliveryAddress: '',
    destinationAddress: '',
    transportWay: '',
    goodsName: '',
    quantity: '',
    effectiveness: null,
    notes: null,
    validity: '',
    companyName: user.companyName,
    linkman: '',
    linkphone: '',
    status: 1,
    remark: null,
    transportCategory: '',
  });
  useEffect(() => {
    async function fetchData() {
      const stair = await getSite({ areaCode: 0 });
      if (stair.code === 0) {
        setSite([
          {
            value: '',
            label: '请选择',
          },
          ...stair.rows,
        ]);
        setProvince([
          {
            value: '',
            label: '请选择',
          },
          ...stair.rows,
        ]);
      }
    }
    fetchData();
  }, []);
  useEffect(() => {
    async function fetchData() {
      const dic1 = await getDicType({ value: 'transportCategory' }); // 运输类型
      const dic2 = await getDicType({ value: 'natTransportType' }); // 常温运输方式
      const dic3 = await getDicType({ value: 'coldTransportType' }); // 冷链运输方式
      if (dic1.code === 0) {
        setType([...dic1.rows]);
      }
      if (dic2.code === 0) {
        setNatWay([...dic2.rows]);
      }
      if (dic3.code === 0) {
        setColdWay([...dic3.rows]);
      }
    }
    fetchData();
  }, []);
  // 运输方式的单选按钮
  function handleTransportRadio(val) {
    setObj({
      ...obj,
      transportCategory: val,
    });
    switch (val) {
      case '01':
        setWay(
          natWay.map(item => {
            return {
              value: item.value,
              label: item.name,
            };
          }),
        );
        break;
      case '02':
        setWay(
          coldWay.map(item => {
            return {
              value: item.value,
              label: item.name,
            };
          }),
        );
        break;
    }
  }
  // 选择时间的单选
  function handleTimeRadio(val) {
    if (val === '01') {
      setShowValidity(false);
      let date = new Date();
      date.setFullYear(date.getFullYear() + 1);
      setObj({
        ...obj,
        validity: transTime(date),
      });
    } else {
      setShowValidity(true);
      setObj({
        ...obj,
        validity: '',
      });
    }
    setValidityType(val);
  }
  function handleOnChange(v, label, field) {
    let val;
    switch (label) {
      case '发货地':
        val = v.length > 0 ? v.join(',') : '';
        break;
      case '目的地':
        val = v.length > 0 ? v.join(',') : '';
        break;
      case '发运量(吨或方)':
        val = v + unit;
        break;
      case '有效期':
        val = transTime(v);
        break;
      case '运输方式':
        val = v[0];
        break;
      default:
        val = v;
    }
    setObj({
      ...obj,
      [field]: val,
    });
  }
  async function handleOnPickerChange(val) {
    if (val.length === 1 && val[0] !== '') {
      const secound = await getSite({ areaCode: val[0] });
      if (secound.code === 0) {
        let arr = province.map(item => {
          if (item.value === val[0]) {
            item.children = [
              {
                value: '',
                label: '请选择',
              },
              ...secound.rows,
            ];
          }
          return item;
        });
        setSite(arr);
      }
    }
  }
  async function handleSubmit() {
    if (flag) {
      Toast.info('不可重复提交', 1);
      return;
    }
    if (Object.values(obj).some(item => item === '')) {
      Toast.info('请填写完整信息', 1);
      return;
    }
    let validityTime = new Date(obj.validity);
    if (validityType === '02' && validityTime >= current + oneYear) {
      Toast.info('选择有效期不能大于等于一年', 1);
      return;
    }
    setFlag(true);
    const res = await addSupply({ ...obj });
    if (res.code === 0) {
      Toast.success(res.msg, 1, () => {
        history.push('/');
      });
    } else {
      setFlag(false);
    }
  }
  return (
    <div className="supply-add">
      <SelfHead title="货源需求发布" />
      <div className="supply-add-body">
        <div className="supply-add-body_form">
          <List className="self-list">
            <Cascade
              label="发货地"
              title="请选择发货地"
              data={site}
              cols={2}
              handleOnChange={handleOnChange}
              handleOnPickerChange={handleOnPickerChange}
              field="deliveryAddress"
            />
            <Cascade
              label="目的地"
              title="请选择目的地"
              data={site}
              cols={2}
              handleOnChange={handleOnChange}
              handleOnPickerChange={handleOnPickerChange}
              field="destinationAddress"
            />
            <div className="transport">
              <div className="transport-title">
                <Star />
                <span>运输类别</span>
              </div>
              <div className="transport-radio">
                <SelfRadio
                  radioData={type}
                  handleRadioChange={handleTransportRadio}
                />
              </div>
            </div>
            <Cascade
              label="运输方式"
              title="请选择运输方式"
              data={way}
              cols={1}
              handleOnChange={handleOnChange}
              field="transportWay"
            />
            <SelfInput
              label="品名"
              rule={{ len: 1, empty: '请输入品名', error: '请正确输入品名' }}
              handleInputChange={handleOnChange}
              field="goodsName"
            />
            <div className="the-name">
              <SelfInput
                label="发运量(吨或方)"
                rule={{
                  len: 1,
                  empty: '请输入发运量',
                  error: '请正确输入发运量',
                  reg: /^\d+(\.\d+)?$/,
                }}
                handleInputChange={handleOnChange}
                field="quantity"
                type="digit"
              />
              <span
                className="unit"
                onClick={() => setUnit(unit === '吨' ? '方' : '吨')}
              >
                {unit}
              </span>
            </div>
            <SelfInput
              label="运输时效"
              isRequired={false}
              rule={{
                len: 0,
                empty: '',
                error: '请输入正确的运输时效',
                reg: /^\d+(\.\d+)?$/,
              }}
              handleInputChange={handleOnChange}
              field="effectiveness"
              unit="小时"
              type="digit"
            />
            <SelfInput
              label="注意事项"
              isRequired={false}
              rule={{ len: 0, empty: '', error: '' }}
              handleInputChange={handleOnChange}
              field="notes"
            />
            <div className="transport">
              <div className="transport-title">
                <Star />
                <span>有效期</span>
              </div>
              <div className="transport-radio">
                <SelfRadio
                  radioData={[
                    {
                      value: '01',
                      name: '长期有效（最长一年）',
                    },
                    {
                      value: '02',
                      name: '短期有效（请选择失效日期）',
                    },
                  ]}
                  handleRadioChange={handleTimeRadio}
                />
              </div>
              {showValidity ? (
                <TimePicker
                  label="有效期"
                  handleOnChange={handleOnChange}
                  field="validity"
                />
              ) : null}
            </div>
            <SelfInput
              label="企业名称"
              rule={{
                len: 2,
                empty: '请输入企业名称',
                error: '请正确输入企业名称',
              }}
              handleInputChange={handleOnChange}
              field="companyName"
              defaultValue={obj.companyName}
              disabled={true}
            />
            <SelfInput
              label="联系人"
              rule={{
                len: 2,
                empty: '请输入联系人',
                error: '请正确输入联系人',
              }}
              handleInputChange={handleOnChange}
              field="linkman"
            />
            <SelfInput
              label="联系电话"
              rule={{
                len: 2,
                empty: '请输入联系电话',
              }}
              handleInputChange={handleOnChange}
              field="linkphone"
            />
          </List>
        </div>
        <div className="supply-add-btn" onClick={handleSubmit}>
          发布
        </div>
      </div>
    </div>
  );
}
export default createForm()(Add);
